import React, { Component } from "react";
import MainLayout from "../../../component/mainLayout/mainLayout";
import { createForm } from "rc-form";
import { connect } from "react-redux";
import Button from "../../../component/button/index";
import { Picker, List, Toast, InputItem, Radio } from "antd-mobile";
import yhTools from "../../../tools/yh";
import { InterfaceG } from "../../../config/Config";
import { openSelectAddress } from "../../../tools/native/navigate.js";
import "./index.scss";
import BackModal from "../../../component/backModal/index";
import themeUtil from "../../../tools/theme";
import Notice from "../../../component/notice/notice";
const emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
const addressReg = /('|"|\\|%|&|<|>|(\\))/g;
import { checkBonus } from "@redux/Action/bank/bank";
const emojiReg = /(\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff])/g;

const backHomeMap = {
	601: "/xhfHomeNoCredit",
	802: "/xhdHome",
	1: "/walletHome",
	602: "/xhfHomeNoCredit"
};

@connect(
	state => ({
		bonusStr: state.bankReducer.bonusStr,
		applyNo: state.getAppPlatformsDatas.applyNo,
		lnid: state.getAppPlatformsDatas.lnid,
		contactInfo: state.contactInfoReducer.contactInfo,
		devicesInfo: state.getAppPlatformsDatas.devicesInfo
	}),
	dispatch => ({
		checkBonus: (val1, val2) => dispatch(checkBonus(val1, val2))
	})
)
class EditPersonalInfo extends Component {
	constructor(props) {
		super(props);
		this.state = {
			companyName: "",
			userAddressDetail: "",
			userAddress: "",
			provinceCode: "",
			province: "",
			cityCode: "",
			city: "",
			countyAreaCode: "",
			countyArea: "",
			longitude: "",
			latitude: "",
			email: "",
			isLoan: "",
			monthIncome: "",
			educateSituation: "",
			jobStatus: "",
			education: [
				{
					label: "硕士及以上",
					value: "05-硕士及以上"
				},
				{
					label: "本科",
					value: "04-本科"
				},
				{
					label: "大专",
					value: "03-大专"
				},
				{
					label: "高中",
					value: "02-高中"
				},
				{
					label: "中专",
					value: "01-中专"
				},
				{
					label: "初中及以下",
					value: "00-初中及以下"
				}
			],
			income: [
				{
					label: "1万以上",
					value: "03-1万以上"
				},
				{
					label: "6千—1万",
					value: "02-6千—1万"
				},
				{
					label: "5千—6千",
					value: "01-5千—6千"
				},
				{
					label: "2千以下",
					value: "00-2千以下"
				}
			],
			hasDebt: [
				{
					label: "有",
					value: "00"
				},
				{
					label: "没有",
					value: "01"
				}
			],
			job: [
				{
					label: "全职有薪",
					value: "00-全职有薪"
				},
				{
					label: "实习或兼职",
					value: "01-实习或兼职"
				},
				{
					label: "个体",
					value: "02-个体"
				},
				{
					label: "自由职业",
					value: "03-自由职业"
				}
				// {
				// 	label: "学生",
				// 	value: "04-学生"
				// }
			],
			isVisible: false,
			canSubmit: true,
			spaceID: "" // 随记生成一个计数
		};
	}
	next = () => {
		this.checkData() && this.saveInfoRequest();
	};
	componentDidMount() {
		this.initFun();
	}
	initFun = () => {
		this.initData();
		if (window.YHAuthorize) {
			window.YHAuthorize.View.addEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
		let _tempRandom = Math.round(Math.random() * 1000000);
		this.setState({
			spaceID: _tempRandom
		});
	};
	componentWillUnmount() {
		if (window.YHAuthorize) {
			window.YHAuthorize.View.removeEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
	}
	keyboardEvent = obj => {
		let winHeight = document.documentElement.clientHeight;
		document.getElementById(`keybordb_${this.state.spaceID}`).style.height =
			winHeight * obj.heightper + "px";
		if (document.activeElement.getAttribute("id") !== "js-fix-bug") {
			document.activeElement.scrollIntoView();
		}
	};
	initData = () => {
		const { applyNo, lnid } = this.props;
		const obj = {
			url: InterfaceG.initUserInfo1,
			params: {
				applyNo,
				lnid
			}
		};
		Toast.loading("加载中...", 100);
		yhTools.request(obj).then(res => {
			Toast.hide();
			if (res.code === "0" && Object.keys(res.data).length) {
				const {
					isLoan,
					email,
					userAddress,
					userAddressDetail,
					companyName,
					provinceCode,
					province,
					cityCode,
					city,
					countyAreaCode,
					countyArea,
					longitude,
					latitude
				} = res.data;
				const data = res.data;
				const jobStatus = `${data.jobStatusCode}-${data.jobStatus}`;
				const educateSituation = `${data.educateSituationCode}-${data.educateSituation}`;
				const monthIncome = `${data.monthIncomeCode}-${data.monthIncome}`;
				this.props.form.setFieldsValue({
					educateSituation: [educateSituation],
					monthIncome: [monthIncome],
					jobStatus: [jobStatus]
				});
				this.setState({
					educateSituation,
					monthIncome,
					isLoan,
					email,
					userAddress,
					userAddressDetail,
					jobStatus,
					companyName,
					provinceCode,
					province,
					cityCode,
					city,
					countyAreaCode,
					countyArea,
					longitude,
					latitude
				});
			} else {
				// 没有初始化数据
			}
			//获取602完善资料奖励
			this.props.checkBonus("60203");
		});
	};
	checkData = () => {
		const {
			educateSituation,
			monthIncome,
			isLoan,
			email,
			userAddress,
			userAddressDetail,
			jobStatus,
			companyName
		} = this.state;
		const { contactInfo } = this.props;
		if (!educateSituation) {
			Toast.info("请选择学历", 2);
			return false;
		}
		if (!monthIncome) {
			Toast.info("请选择月收入", 2);
			return false;
		}
		if (!isLoan) {
			Toast.info("请选择是否有信用卡或房贷", 2);
			return false;
		}
		if (email && !emailReg.test(email) && !yhTools.isXiaoHuiFu()) {
			Toast.info("请输入正确的邮箱", 2);
			return false;
		}
		if (!userAddress) {
			Toast.info("请选择现居地址", 2);
			return false;
		}
		if (!userAddressDetail) {
			Toast.info("请选填写具体街道门牌号", 2);
			return false;
		}
		if (!Object.keys(contactInfo).length) {
			Toast.info("请添加紧急联系人", 2);
			return false;
		}
		if (!jobStatus) {
			Toast.info("请选择就业状态", 2);
			return false;
		}
		const hasJob = jobStatus === "00-全职有薪" || jobStatus === "01-实习或兼职";
		if (hasJob && !companyName && !yhTools.isXiaoHuiFu()) {
			Toast.info("请填写单位名称", 2);
			return false;
		}
		return true;
	};
	//pickView 选择数据获取
	setValue = (type, key, value) => {
		key === "userAddressDetail" && (value = value.replace(addressReg, ""));

		(key === "email" || key === "userAddressDetail" || key === "companyName") &&
			(value = value.replace(emojiReg, ""));
		this.setState({
			[key]: type === "picker" ? value[0] : value
		});
	};
	jumpContact = () => {
		//记录跳转到了联系人session，返回时判断session值，是否重新请求数据  1是，0不是；
		sessionStorage.setItem("isFromContact", "1");
		this.props.history.push("/editContactInfo");
	};
	openMap = () => {
		// TODO测试数据
		// const adcode = "909089";
		// this.setState({
		//     latitude: "21",
		//     longitude: "106",
		//     userAddress: "测试地址",
		//     userAddressDetail: "测试地址详情",
		//     province: "测试省",
		//     city: "测试城市",
		//     countyArea: "测试区域",
		//     provinceCode: String(adcode).slice(0, 2),
		//     cityCode: String(adcode).slice(2, 4),
		//     countyAreaCode: String(adcode).slice(4, 6)
		// });
		openSelectAddress().then(res => {
			if (res.status === "1000") {
				const {
					lat,
					lng,
					adcode,
					province,
					city,
					district,
					title,
					address
				} = res.data;
				this.setState({
					latitude: lat,
					longitude: lng,
					userAddress: title,
					userAddressDetail: address,
					province,
					city,
					countyArea: district,
					provinceCode: "", //String(adcode).slice(0, 2),
					cityCode: "", //String(adcode).slice(2, 4),
					countyAreaCode: "" // String(adcode).slice(4, 6)
				});
			} else {
				Toast.info(res.data.message, 5);
			}
		});
	};
	saveInfoRequest = () => {
		if (!this.state.canSubmit) return;
		this.setState({
			canSubmit: false
		});
		const { applyNo, lnid } = this.props;
		const {
			educateSituation,
			monthIncome,
			isLoan,
			email,
			userAddress,
			userAddressDetail,
			jobStatus,
			companyName,
			provinceCode,
			province,
			cityCode,
			city,
			countyAreaCode,
			countyArea,
			longitude,
			latitude
		} = this.state;
		const hasJob = jobStatus === "00-全职有薪" || jobStatus === "01-实习或兼职";
		const obj = {
			url: InterfaceG.saveUserInfo1,
			params: {
				applyNo,
				lnid,
				educateSituationCode: educateSituation.split("-")[0],
				educateSituation: educateSituation.split("-")[1],
				monthIncome: monthIncome.split("-")[1],
				monthIncomeCode: monthIncome.split("-")[0],

				isLoan,
				email: email.length ? email : undefined,
				userAddress,
				userAddressDetail,
				jobStatusCode: jobStatus.split("-")[0],
				jobStatus: jobStatus.split("-")[1],
				companyName: !hasJob ? undefined : companyName,
				provinceCode,
				province,
				cityCode,
				city,
				countyAreaCode,
				countyArea,
				longitude,
				latitude
			}
		};
		if (yhTools.isXiaoHuiFu()) {
			delete obj.params.email;
			delete obj.params.companyName;
		}
		Toast.loading("加载中...", 100);
		yhTools.request(obj).then(res => {
			this.setState({ canSubmit: true });
			Toast.hide();
			if (res.code === "0") {
				//判断是生活app
				if (themeUtil.getTheme() == "yhLife" && lnid == "602") {
					this.xhfAppSubApply();
				} else {
					this.props.history.push("/xhfOpenSuccess");
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	};
	onModalClick = booleanValue => {
		this.setState({
			isVisible: false
		});
		!booleanValue && this.props.history.push(backHomeMap[this.props.lnid]);
	};
	showModal = () => {
		this.setState({
			isVisible: true
		});
	};
	//科罗纳调授信接口
	xhfAppSubApply() {
		let objs = {
			url: InterfaceG.yhbXhfApply,
			params: {
				productNum: "601",
				userDeviceInfo: JSON.stringify(this.props.devicesInfo)
			}
		};
		let _that = this;
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				const status = res.data.applyStatus;
				if (status == "1") {
					_that.props.history.push({
						pathname: "/xhfFacilitySuccess"
					});
				} else if (status == "4") {
					_that.props.history.push({
						pathname: "/xhfOpenFail",
						state: { message: res.data.message }
					});
				} else if (status == "2" || status == "3") {
					//授信中
					//科罗纳去10秒倒计时页面
					_that.props.history.push("/xhfLivenessRet");
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	render() {
		const _pageParams = {
			header: {
				title: "完善资料"
			},
			componentDidRecover: () => {
				// 缓存
				//如果是联系人页返回，不重新初始化
				let isFromContact = sessionStorage.getItem("isFromContact");
				if (isFromContact == "1") {
					sessionStorage.removeItem("isFromContact");
					return false;
				}
				this.initFun();
			},
			isModal: true,
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles
		};

		const {
			education,
			job,
			jobStatus,
			income,
			hasDebt,
			isLoan,
			email,
			userAddress,
			companyName,
			userAddressDetail,
			isVisible
		} = this.state;
		const { getFieldProps } = this.props.form;
		const { lnid, contactInfo, bonusStr } = this.props;
		const hasEmergencyConact = Object.keys(contactInfo).length;
		const hasJob = jobStatus === "00-全职有薪" || jobStatus === "01-实习或兼职";
		return (
			<MainLayout pageParams={_pageParams} handleBack={this.showModal}>
				<BackModal
					product={lnid}
					isVisible={isVisible}
					onClick={this.onModalClick}
				/>
				<div>
					<div className="edit-person-info-wrapper">
						{bonusStr && <Notice noticeContent={bonusStr} />}
						{/*  yhTools.isXiaoHuiFu()&&*/}
						{yhTools.isXiaoHuiFu() && (
							<div className="progress-container">
								<p className="progress-title">
									已填写 <em>99%</em> 最高5万元信用额度
								</p>
								<div className="progress-bg">
									<span className="progress-line"></span>
								</div>
							</div>
						)}
						<div className="remind">
							<p className="remind-tip">
								请确保所填信息完整、真实有效、以便于快速审核
							</p>
						</div>

						<List className="person-info-list">
							<Picker
								extra="请选择学历"
								data={education}
								title=""
								cols={1}
								{...getFieldProps("educateSituation")}
								onOk={this.setValue.bind(this, "picker", "educateSituation")}
							>
								<List.Item arrow="horizontal">学历</List.Item>
							</Picker>
							<Picker
								extra="请选择月收入"
								data={income}
								title=""
								cols={1}
								{...getFieldProps("monthIncome")}
								onOk={this.setValue.bind(this, "picker", "monthIncome")}
							>
								<List.Item arrow="horizontal">收入</List.Item>
							</Picker>
							<List.Item
								className="long-list"
								extra={hasDebt.map(item => (
									<Radio
										key={item.value}
										checked={item.value === isLoan}
										className="my-radio"
										onChange={this.setValue.bind(
											this,
											"input",
											"isLoan",
											item.value
										)}
									>
										{item.label}
									</Radio>
								))}
							>
								是否有信用卡或房贷
							</List.Item>
						</List>

						<List className="person-info-list person-info-list-2">
							{!yhTools.isXiaoHuiFu() && (
								<InputItem
									maxLength="30"
									id="js-fix-bug"
									name="input"
									placeholder="请输入常用邮箱（选填）"
									value={email}
									onChange={this.setValue.bind(this, "input", "email")}
								>
									常用邮箱
								</InputItem>
							)}
							<List.Item
								extra={!userAddress ? "请选择现居地址" : userAddress}
								arrow="horizontal"
								onClick={this.openMap}
							>
								现居地址
							</List.Item>
							<InputItem
								maxLength="50"
								// autoHeight
								type="text"
								placeholder="请填写具体街道 门牌号"
								value={userAddressDetail}
								onChange={this.setValue.bind(
									this,
									"input",
									"userAddressDetail"
								)}
							/>
							{/* <span style={{ opacity: 0 }}>详细地址</span>
                            </InputItem> */}
							<List.Item
								extra={hasEmergencyConact ? "联系人信息" : "非紧急情况不会联系"}
								arrow="horizontal"
								onClick={this.jumpContact}
							>
								紧急联系人
							</List.Item>
							<Picker
								extra="请选择就业状态"
								data={job}
								title=""
								cols={1}
								{...getFieldProps("jobStatus")}
								onOk={this.setValue.bind(this, "picker", "jobStatus")}
							>
								<List.Item arrow="horizontal">就业状态</List.Item>
							</Picker>
							{hasJob && !yhTools.isXiaoHuiFu() && (
								<InputItem
									maxLength="50"
									type="text"
									placeholder="请填写单位名称"
									value={companyName}
									onChange={this.setValue.bind(this, "input", "companyName")}
								>
									单位名称
								</InputItem>
							)}
						</List>

						<Button
							style={{
								marginTop: "0.2rem"
							}}
							buttonStyle={{
								height: "1rem",
								lineHeight: "1rem"
							}}
							onClick={this.next}
						>
							下一步
						</Button>
					</div>
					<div id={"keybordb_" + this.state.spaceID}></div>
				</div>
			</MainLayout>
		);
	}
}

export default createForm()(EditPersonalInfo);
